package com.xys.auth.controller;

import com.xys.auth.bean.Role;
import com.xys.auth.bean.UserInfo;
import com.xys.auth.service.IRoleService;
import com.xys.auth.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.rmi.MarshalledObject;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    @RequestMapping("/findAll.do")
    public ModelAndView findAll(){
        List<UserInfo> users = userService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user-list");
        modelAndView.addObject("userList",users);
        return modelAndView;
    }

    @RequestMapping("/save.do")
    public String save(UserInfo userInfo){


        userInfo.setId(UUID.randomUUID().toString().replace("-",""));
        userService.save(userInfo);

        return "redirect:findAll.do";
    }

    @RequestMapping("/findById.do")
    public ModelAndView findById(String id){
        ModelAndView modelAndView = new ModelAndView();
        UserInfo userInfo = userService.findById(id);

        modelAndView.setViewName("user-show");
        modelAndView.addObject("user",userInfo);
        return modelAndView;
    }

    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(String id){
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        List<Role> otherRole = roleService.findOtherRole(id);
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("user-role-add");
        modelAndView.addObject("roleList",otherRole);
        modelAndView.addObject("user",userInfo);
        return modelAndView;
    }

    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(String userId,String[] ids){

        userService.addRoleToUser(userId,ids);

        return "redirect:findAll.do";

    }
}
